#include "DocumentSymbol.h"
#include "simodo/lsp-server/ServerContext.h"
#include "simodo/lsp-server/DocumentContext.h"

#include "simodo/variable/json/Rpc.h"
#include "simodo/variable/json/Serialization.h"
#include "simodo/inout/convert/functions.h"

namespace simodo::lsp
{

void DocumentSymbol::work()
{
    if (_jsonrpc.is_valid()) {
        const variable::Value & params_value = _jsonrpc.params();
        if (params_value.type() == variable::ValueType::Object) {
            std::string uri;
            std::shared_ptr<variable::Object> params_object = params_value.getObject();
            const variable::Value & textDocument_value  = params_object->find(u"textDocument");
            if (textDocument_value.type() == variable::ValueType::Object) {
                const variable::Value & uri_value = textDocument_value.getObject()->find(u"uri");
                if (uri_value.type() == variable::ValueType::String)
                    uri = inout::toU8(uri_value.getString());
            }

            if (!uri.empty()) {
                DocumentContext * doc = _server.findDocument(uri);
                if (doc) {
                    variable::Value result = doc->produceDocumentSymbolsResponse();
                    _server.sending().push(variable::JsonRpc(result, _jsonrpc.id()));
                    return;
                }
                _server.log().error("'textDocument/documentSymbol' command: uri '" + uri + "' don't loaded yet",
                                    variable::toJson(_jsonrpc.value()));
                _server.sending().push(
                    /// @todo Скорректировать коды (и тексты) ошибок
                    variable::JsonRpc(-1,
                        u"'textDocument/documentSymbol' command: uri '" + inout::toU16(uri) + u"' don't loaded yet",
                        _jsonrpc.id()));
                return;
            }
        }
    }
    _server.log().error("There are wrong parameter structure of 'textDocument/documentSymbol' command", 
                        variable::toJson(_jsonrpc.value()));
    _server.sending().push(
        /// @todo Скорректировать коды (и тексты) ошибок
        variable::JsonRpc(-1,u"There are wrong parameter structure of 'textDocument/documentSymbol' command",
                            _jsonrpc.id()));
}

}